package core.base.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.util.WebUtils;

import util.ConvertRegisterHelper;

import cn.org.rapid_framework.page.PageRequest;

public class BasePageRequest extends PageRequest<Object> {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5202597221685561549L;

	private Map<String, Object> params;

	public static final int MAX_PAGE_SIZE = 1000;
	public static final int DEFAULT_PAGE_SIZE = 10;

	static BeanUtilsBean beanUtils = new BeanUtilsBean();
	static {
		// 用于注册日期类型的转换
		String[] datePatterns = new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS",
				"HH:mm:ss" };
		ConvertRegisterHelper.registerConverters(beanUtils.getConvertUtils(), datePatterns);

		System.out.println("PageRequestFactory.MAX_PAGE_SIZE=" + MAX_PAGE_SIZE);
	}

	public static BasePageRequest bindRequest(HttpServletRequest request) {
		return bindRequest(request, null);
	}

	public static BasePageRequest bindRequest(HttpServletRequest request, String defaultSortColumns) {
		return bindRequest(request, defaultSortColumns, DEFAULT_PAGE_SIZE);
	}

	/**
	 * 绑定PageRequest的属性值
	 */
	public static BasePageRequest bindRequest(HttpServletRequest request, String defaultSortColumns,
			int defaultPageSize) {
		BasePageRequest pageRequest = new BasePageRequest();

		Map<String, Object> params = WebUtils.getParametersStartingWith(request, "");
		pageRequest.setParams(params);

		pageRequest.setPageNumber(ServletRequestUtils.getIntParameter(request, "pageNum", 1));
		pageRequest.setPageSize(ServletRequestUtils.getIntParameter(request, "numPerPage", defaultPageSize));
		pageRequest.setSortColumns(ServletRequestUtils.getStringParameter(request, "orderField", defaultSortColumns));

		if (pageRequest.getPageSize() > MAX_PAGE_SIZE) {
			pageRequest.setPageSize(MAX_PAGE_SIZE);
		}
		return pageRequest;
	}

	public Map<String, Object> getParams() {
		return params;
	}

	public void setParams(Map<String, Object> params) {
		this.params = params;
	}

	public Object getParamAsString(String paramName) {
		return (String) params.get(paramName);
	}

}
